package Controller

import (
	"back_go/Common"
	"back_go/DAO"
	models "back_go/DAO/model"
	"back_go/Response"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
)

type User struct {
	Email      string   `json:"email"`
	Username   string   `json:"username"`
	UserId     string   `json:"userId"`
	Password   string   `json:"password"`
	Mobile     string   `json:"mobile"`
	Status     string   `json:"status"`
	ShopId     string   `json:"shopId"`
	RoleIdList []string `json:"roleIdList"`
	CreateTime string   `json:"createTime"`
}

// SaveSysUser 管理员新增
/*
 {}   管理员新增
 	参数：User 结构体
			email: 邮箱
			username: 用户名
			password: 密码
			mobile: 手机号
			status: 状态
			shopId: 店铺id
			roleIdList: 角色id集合
			createTime: 创建时间
	返回：
		Response.ResponseBody    响应体
*/
func SaveSysUser(c *gin.Context) {
	var engine = DAO.Engine
	var User User
	_ = c.ShouldBindJSON(&User)
	session := engine.NewSession()
	defer session.Close()

	// 开启事务
	err := session.Begin()
	var sysUser models.TzSysUser
	sysUser.Email = User.Email
	sysUser.Username = User.Username
	sysUser.Password = User.Password
	sysUser.Mobile = User.Mobile
	sysUser.Status, _ = strconv.Atoi(User.Status)
	sysUser.ShopId, _ = strconv.ParseInt(User.ShopId, 10, 64)
	sysUser.CreateTime = time.Now()

	//判断用户名是否已存在
	has, _ := engine.SQL("select * from tz_sys_user where username = ?", sysUser.Username).Exist()
	if has {
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "A00001",
			Msg:       "该用户已存在",
			Data:      nil,
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Success:   false,
			Fail:      true,
		})
		return
	}
	sysUser.CreateTime = time.Now()

	//加密密码
	sysUser.Password, _ = Common.AESEncrypt([]byte(sysUser.Password))
	_, err = engine.Insert(sysUser)
	if err != nil {
		c.JSON(http.StatusInternalServerError, Response.ResponseBody{
			Code:      "A00005",
			Msg:       "服务器出了点小差",
			Data:      false,
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Success:   false,
			Fail:      true,
		})
		return
	}

	var sysUser1 models.TzSysUser
	_, _ = engine.Where("username=?", sysUser.Username).Get(&sysUser1)
	//插入用户角色关联表
	if User.RoleIdList[0] == "1" {

		_, _ = engine.Insert(&models.TzSysUserRole{
			UserId: sysUser1.UserId,
			RoleId: 1,
		})
	}

	// 提交事务
	err = session.Commit()
	if err != nil {
		c.JSON(http.StatusInternalServerError, Response.ResponseBody{
			Code:      "A00001",
			Msg:       "数据库插入失败",
			Data:      nil,
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Success:   false,
			Fail:      true,
		})
		return
	}

	c.JSON(http.StatusOK, Response.ResponseBody{
		Code:      "A00000",
		Msg:       "保存成功",
		Data:      nil,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
		Success:   true,
		Fail:      false,
	})
}

// UpdateSysUser 管理员修改
func UpdateSysUser(c *gin.Context) {
	var engine = DAO.Engine
	var User User
	_ = c.ShouldBindJSON(&User)
	session := engine.NewSession()
	defer session.Close()

	// 开启事务
	err := session.Begin()
	var sysUser models.TzSysUser
	sysUser.Email = User.Email
	sysUser.Username = User.Username
	sysUser.Password = User.Password
	sysUser.Mobile = User.Mobile
	sysUser.Status, _ = strconv.Atoi(User.Status)
	sysUser.ShopId, _ = strconv.ParseInt(User.ShopId, 10, 64)
	sysUser.CreateTime = time.Now()

	//判断用户名是否已存在
	has, _ := engine.SQL("select * from tz_sys_user where username = ?", sysUser.Username).Exist()
	if has == false {
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "A00001",
			Msg:       "该用户不存在",
			Data:      nil,
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Success:   false,
			Fail:      true,
		})
		return
	}
	sysUser.CreateTime = time.Now()

	//加密密码
	sysUser.Password, _ = Common.AESEncrypt([]byte(sysUser.Password))
	//_, err = engine.Insert(sysUser)
	_, err = engine.Table("tz_sys_user").Where("username = ?", sysUser.Username).Update(&sysUser)
	if err != nil {
		c.JSON(http.StatusInternalServerError, Response.ResponseBody{
			Code:      "A00005",
			Msg:       "服务器出了点小差",
			Data:      false,
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Success:   false,
			Fail:      true,
		})
		return
	}

	var sysUser1 models.TzSysUser
	_, _ = engine.Where("username=?", sysUser.Username).Get(&sysUser1)
	//插入用户角色关联表
	if User.RoleIdList[0] == "1" {

		_, _ = engine.Insert(&models.TzSysUserRole{
			UserId: sysUser1.UserId,
			RoleId: 1,
		})
	}

	// 提交事务
	err = session.Commit()
	if err != nil {
		c.JSON(http.StatusInternalServerError, Response.ResponseBody{
			Code:      "A00001",
			Msg:       "数据库插入失败",
			Data:      nil,
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Success:   false,
			Fail:      true,
		})
		return
	}

	c.JSON(http.StatusOK, Response.ResponseBody{
		Code:      "A00000",
		Msg:       "保存成功",
		Data:      nil,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
		Success:   true,
		Fail:      false,
	})
}

// DelSysUser 管理员删除
func DelSysUser(c *gin.Context) {
	var engine = DAO.Engine
	var sysUser models.TzSysUser
	var jsonData []string
	session := engine.NewSession()
	defer session.Close()

	// 开启事务
	err := session.Begin()
	if err := c.ShouldBindJSON(&jsonData); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	// 这里假设你的 JSON 数据格式就是一个字符串数组，直接赋值给列表
	list := jsonData
	// 打印列表中的每个字符串
	for i := range list {
		fmt.Println(i)
		_, _ = engine.Table("tz_sys_user").Where("user_id = ?", list[i]).Delete(&sysUser)
	}

	if err != nil {

		c.JSON(http.StatusInternalServerError, Response.ResponseBody{
			Code:      "A00001",
			Msg:       "数据库插入失败",
			Data:      nil,
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Success:   false,
			Fail:      true,
		})
		return
	}
	err = session.Commit()
	c.JSON(http.StatusOK, Response.ResponseBody{
		Code:      "A00000",
		Msg:       "删除成功",
		Data:      nil,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
		Success:   true,
		Fail:      false,
	})
}

type password struct {
	Password    string `json:"password"`
	Newpassword string `json:"newPassword"`
}

// ChangeSysPassword 修改密码
func ChangeSysPassword(c *gin.Context) {
	var engine = DAO.Engine
	var TzSysUser models.TzSysUser
	var password password
	err := c.ShouldBindJSON(&password)

	authHeader := c.Request.Header.Get("Authorization")
	UserId, _, err := Common.CodeToken(authHeader)

	if err != nil {
		c.JSON(http.StatusInternalServerError, Response.ResponseBody{
			Code:      "A00004",
			Msg:       "Unauthorized",
			Data:      false,
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Success:   false,
			Fail:      true,
		})

		return
	}
	_, _ = engine.Where("user_id=?", UserId).Get(&TzSysUser)

	jiemi, _ := Common.AESDecrypt(TzSysUser.Password)

	if jiemi != password.Password {
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "A00001",
			Msg:       "密码错误",
			Data:      false,
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Success:   false,
			Fail:      true,
		})
		return
	}

	TzSysUser.Password, _ = Common.AESEncrypt([]byte(password.Newpassword))
	_, err = engine.Where("user_id=?", UserId).Update(&TzSysUser)
	if err != nil {
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "A00005",
			Msg:       "服务器出了点小差",
			Data:      false,
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Success:   false,
			Fail:      true,
		})
		fmt.Println("无法更新")
		return
	}
	c.JSON(http.StatusOK, Response.ResponseBody{
		Code:      "00000",
		Msg:       "修改成功",
		Data:      nil,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
		Success:   true,
	})
}

type PageParam[T any] struct {
	Username    string      `json:"username"`
	Size        int         `json:"size"`
	Current     int         `json:"current"`
	Records     interface{} `json:"records"`
	Total       int64       `json:"total"`
	SearchCount bool        `json:"searchCount"`
	Pages       int64       `json:"pages"`
}

// GetSysUserPage 按照用户名查询
func GetSysUserPage(c *gin.Context) {
	var engine = DAO.Engine
	var pageParam PageParam[models.TzSysUser]

	pageParam.Username = c.Query("username")
	pageParam.Size, _ = strconv.Atoi(c.Query("size"))
	pageParam.Current, _ = strconv.Atoi(c.Query("current"))

	if err := c.ShouldBind(&pageParam); err != nil {
		c.JSON(200, Response.ResponseBody{
			Code:      "A00002",
			Msg:       "没有数据",
			Data:      nil,
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "", // 根据你的业务逻辑生成签名
			Success:   false,
			Fail:      true,
		})
		return
	}

	if pageParam.Size == 0 {
		pageParam.Size = 10
	}

	if pageParam.Current == 0 {
		pageParam.Current = 1
	}

	pageSize := pageParam.Size
	pageCurrent := pageParam.Current

	tzSysUser := make([]models.TzSysUser, 0)

	_ = engine.Where("username like ?", "%"+pageParam.Username+"%").Limit(pageSize, pageCurrent-1).Find(&tzSysUser)
	count, _ := engine.Where("username like ?", "%"+pageParam.Username+"%").Count(&models.TzSysUser{})
	if tzSysUser == nil {
		c.JSON(http.StatusInternalServerError, Response.ResponseBody{
			Code:      "00000",
			Msg:       "没有数据",
			Data:      nil,
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      nil,
			Success:   true,
			Fail:      false,
		})
		return
	}

	c.JSON(http.StatusOK, Response.ResponseBody{
		Code: "00000",
		Msg:  nil,
		Data: PageParam[models.TzSysUser]{
			Current:  pageParam.Current,
			Records:  tzSysUser,
			Size:     pageParam.Size,
			Total:    count,
			Username: pageParam.Username,
			Pages:    int64(pageParam.Current),
		},
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
		Success:   true,
		Fail:      false,
	})

}

// GetSysInfoByToken 根据token获取用户信息
func GetSysInfoByToken(c *gin.Context) {
	var engine = DAO.Engine
	var User User
	var sysUser models.TzSysUser
	authHeader := c.Request.Header.Get("Authorization")
	//获取用户id
	UserId, _, _ := Common.CodeToken(authHeader)
	_, err := engine.Where("user_id=?", UserId).Get(&sysUser)
	if err != nil {
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "00000",
			Msg:       "没有数据",
			Data:      nil,
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Success:   true,
			Fail:      false,
		})
	}
	User.UserId = strconv.FormatInt(sysUser.UserId, 10)
	User.Username = sysUser.Username
	User.Email = sysUser.Email
	User.Mobile = sysUser.Mobile
	User.Status = strconv.Itoa(sysUser.Status)
	User.CreateTime = sysUser.CreateTime.Format("2006-01-02 15:04:05")
	User.ShopId = strconv.FormatInt(sysUser.ShopId, 10)

	var userRole models.TzSysUserRole
	_, _ = engine.Where("user_id=?", UserId).Get(&userRole)

	User.RoleIdList = []string{strconv.FormatInt(userRole.RoleId, 10)}
	c.JSON(http.StatusOK, Response.ResponseBody{
		Code:      "00000",
		Msg:       "ok",
		Data:      User,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
		Success:   true,
		Fail:      false,
	})

}

func GetSysInfoById(c *gin.Context) {
	var engine = DAO.Engine

	var User User
	var sysUser models.TzSysUser
	Userid := c.Param("userId")
	fmt.Println(Userid)
	_, err := engine.Where("user_id=?", Userid).Get(&sysUser)
	if err != nil {
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "00000",
			Msg:       "没有数据",
			Data:      nil,
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Success:   true,
			Fail:      false,
		})
		return
	}
	User.UserId = strconv.FormatInt(sysUser.UserId, 10)
	User.Username = sysUser.Username
	User.Email = sysUser.Email
	User.Mobile = sysUser.Mobile
	User.Status = strconv.Itoa(sysUser.Status)
	User.CreateTime = sysUser.CreateTime.Format("2006-01-02 15:04:05")
	User.ShopId = strconv.FormatInt(sysUser.ShopId, 10)

	var userRole models.TzSysUserRole
	_, _ = engine.Where("user_id=?", Userid).Get(&userRole)

	User.RoleIdList = []string{strconv.FormatInt(userRole.RoleId, 10)}

	c.JSON(http.StatusOK, Response.ResponseBody{
		Code:      "00000",
		Msg:       nil,
		Data:      User,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
		Success:   true,
		Fail:      false,
	})
}
